'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const userList = await ctx.service.user.getUserList();
    const roleList = await ctx.service.role.getAllRoleList();
    const list = userList.map(item => {
      const target = roleList.find(role => role.roleId === item.roleId);
      item.roleName = target ? target.roleName : '';
      return item;
    });
    const result = ctx.camelcaseKeys(list);
    ctx.returnBody({
      data: result,
    });
  }

  async create() {
    const { ctx } = this;
    const user = ctx.request.body;
    const result = await ctx.service.user.createUser(user);
    ctx.returnBody({
      data: result,
      message: '创建成功',
    });
  }

  // 获取用户信息
  async info() {
    const { ctx } = this;
    const userId = ctx.request.headers['user-id'];
    // 用户信息
    const user = await ctx.service.user.getUserByUserId(userId);
    if (user) {
      // 学历列表
      const educationList = await ctx.service.education.getList();
      // 年级列表
      const gradeList = await ctx.service.grade.getList();
      ctx.returnBody({
        data: {
          user,
          educationList,
          gradeList,
        },
      });
    } else {
      ctx.returnBody({
        code: 401,
        message: '用户找不到',
      });
    }
  }
}

module.exports = UserController;
